using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Collections.Generic;

namespace BlogEngine.Core
{
	class PhotoManipulation
	{

		#region Photo Manipulation 

		/// <summary>
		/// Resizes the image.
		/// </summary>
		/// <param name="oldimage">The oldimage.</param>
		/// <param name="size">The size.</param>
		/// <returns></returns>
		public static Image ResizeImage(Image oldimage, int size)
		{
			//if no size change requested return the incoming stream
			if (size <= 0)
				return oldimage;

			Size newsize = CalculateDimensions(oldimage.Size, size);
			Bitmap newimage = new Bitmap(newsize.Width, newsize.Height, PixelFormat.Format24bppRgb);

			using (Graphics canvas = Graphics.FromImage(newimage))
			{
				canvas.SmoothingMode = SmoothingMode.AntiAlias;
				canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
				canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
				canvas.DrawImage(oldimage, new Rectangle(new Point(0, 0), newsize));
			}

			return newimage;
		}

		public static Size CalculateDimensions(Size oldSize, int targetSize)
		{
			Size newSize = new Size();
			if (oldSize.Height > oldSize.Width)
			{
				newSize.Width = (int)(oldSize.Width * ((float)targetSize / (float)oldSize.Height));
				newSize.Height = targetSize;
			}
			else
			{
				newSize.Width = targetSize;
				newSize.Height = (int)(oldSize.Height * ((float)targetSize / (float)oldSize.Width));
			}
			return newSize;
		}

		private static ImageCodecInfo GetEncoderInfo(String mimeType)
		{
			ImageCodecInfo[] encoders;
			encoders = ImageCodecInfo.GetImageEncoders();

			for (int idx = 0; idx < encoders.Length; ++idx)
			{
				if (encoders[idx].MimeType == mimeType)
				{
					return encoders[idx];
				}
			}

			return null;
		}

		/// <summary>
		/// Saves the image to stream.
		/// </summary>
		/// <param name="newimage">The image.</param>
		/// <param name="qualitylevel">Quality level.</param>
		/// <returns></returns>
		public static MemoryStream SaveToStream(Image newimage, int qualitylevel)
		{
			// Save the bitmap as a JPEG file
			EncoderParameters myEncoderParameters = new EncoderParameters(1);
			myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, (long)qualitylevel);

			//save new image to file system.
			MemoryStream newStream = new MemoryStream();
			newimage.Save(newStream, GetEncoderInfo("image/jpeg"), myEncoderParameters);

			return newStream;
		}

		#endregion

	}
}
